package com.hbtt.sousou;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

/**
 * @author 窦瑞涛 王冰强 
 * 工具类
 */
public class CardUtil {

	// 已注册的用户列表
	Map<String, MobileCard> card = new HashMap<String, MobileCard>();
	// 所有卡号的消费列表
	Map<String, List<ConsumInfo>> consumInfos = new HashMap<String, List<ConsumInfo>>();
	// 使用场景列表
	Map<Integer, Scene> scenes = new HashMap<Integer, Scene>();
	//消费场景
	List<ConsumInfo> listcon = new ArrayList<ConsumInfo>();
	/**
	 * 注册新卡
	 * 
	 * @param name
	 * @param mobileCard
	 */
	public void addCard(String number, MobileCard mobileCard) {
		card.put(number, mobileCard);
	}

	/**
	 * 话费充值
	 * 
	 * @param number
	 * @param money
	 */
	public void chargeMoney(String number, double money) {
		if (isExistCard(number)) {
			double money1 = card.get(number).getMoney();
			card.get(number).setMoney(money1 + money);
			System.out.println("充值成功，当前话费余额为" + card.get(number).getMoney());
		} else {
			System.out.println("手机号不存在，请先注册");
		}

	}

	/**
	 * 使用嗖嗖
	 * 
	 * @param number
	 */
	public void userSoso(String number) {

		scenes.put(0, new Scene("通话", 90, "问候客户，谁知如此难缠，通话90分钟"));
		scenes.put(1, new Scene("通话", 30, "询问妈妈身体状况，本地通话30分钟"));
		scenes.put(2, new Scene("短信", 5, "参与环境保护实施方案问卷调查，发送短信5条"));
		scenes.put(3, new Scene("短信", 50, "通知朋友手机换号，发送短信50条"));
		scenes.put(4, new Scene("上网", 1*1024, "和女友微信视频聊天，使用流量1GB"));
		scenes.put(5, new Scene("上网", 2*1024, "晚上手机在线看韩剧，不留神睡着啦！使用2GB"));

		MobileCard cards = card.get(number);

		ServicePackage s = cards.getSerPackage();// 所属套餐

		int consum = 0;
		do {
			int num = (int) (Math.random() * 5);

			Scene scene = scenes.get(num);// 获取场景

			switch(num) {
			case 0:
			case 1:
				if (s instanceof CallService) {
					// 输出场景信息
					System.out.println(scene.descripion);
					// 调用打电话的方法，保存返回打了多长时间到consum中
					try {
						consum = ((CallService) s).call(scene.data, cards);
					} catch (Exception e) {
						e.printStackTrace();
					}
					// 添加一条消费记录
					addConsumInfo(number, new ConsumInfo(number, scene.type, consum));
					break;
				} else {
					continue;
				}
			case 2:
			case 3:
				if (s instanceof SendService) {
					System.out.println(scene.descripion);
					try {
						consum = ((SendService) s).send(scene.data, cards);
					} catch (Exception e) {
						e.printStackTrace();
					}
					addConsumInfo(number, new ConsumInfo(number, scene.type, consum));
					break;
				} else {
					continue;
				}
			case 4:
			case 5:
				if (s instanceof NetService) {
					System.out.println(scene.descripion);
					try {
						consum = ((NetService) s).netPlay(scene.data, cards);
					} catch (Exception e) {
						e.printStackTrace();
					}
					addConsumInfo(number, new ConsumInfo(number, scene.type, consum));
					break;
				} else {
					continue;
				}
			}
			break;
		} while (true);
	}

	/**
	 * 资费说明
	 */
	public void showDescripiton() {
		System.out.println("*****资费说明******");
		System.out.println("套餐类型：话唠套餐\n通话时长：500分钟 \n短信条数：30条\n月资费：58元");
		System.out.println("------------------");
		System.out.println("套餐类型：网虫套餐\n上网流量：3GB\n月资费：68元");
		System.out.println("------------------");
		System.out.println("套餐类型：超人套餐\n通话时长：200分钟 \n上网流量：3GB\n短信条数：50条\n月资费：78元");
	}

	/**
	 * 本月账单查询
	 * 
	 * @param number
	 */
	public void showAmountDetail(String number) {
		System.out.println("------本月账单查询------");
		MobileCard cards = card.get(number);
		System.out.println("您的卡号是:" + number + "当月账单：");
		System.out.println("套餐资费" + cards.getSerPackage().getPrice()+"元");
		System.out.println("合计" + (cards.getConsumAmount() + cards.getSerPackage().getPrice())+"元");
		System.out.println("账户余额" + cards.getMoney()+"元");
		System.out.println();
	}

	/**
	 * 套餐余量查询
	 * 
	 * @param number
	 */
	public void showRemainDetail(String number) {
		MobileCard cards = card.get(number);
		int smscount = 0;
		int flow = 0;
		int time = 0;
		if (cards.getSerPackage() instanceof TalkPackage) {
			TalkPackage type = (TalkPackage) cards.getSerPackage();
			if (type.getTalkTime() > cards.getRealTalkTime()) {
				time = type.getTalkTime() - cards.getRealTalkTime();
			} else {
				time = 0;
			}

			if (type.getSmsCount() > cards.getRealSMSCount()) {
				smscount = type.getSmsCount() - cards.getRealSMSCount();
			} else {
				smscount = 0;
			}
		}

		if (cards.getSerPackage() instanceof SuperPackage) {
			SuperPackage type = (SuperPackage) cards.getSerPackage();
			if (type.getTalkTime() > cards.getRealTalkTime()) {
				time = type.getTalkTime() - cards.getRealTalkTime();
			} else {
				time = 0;
			}

			if (type.getSmsCount() > cards.getRealSMSCount()) {
				smscount = type.getSmsCount() - cards.getRealSMSCount();
			} else {
				smscount = 0;
			}

			if (type.getFlow() > cards.getRealFlow()) {
				flow = type.getFlow() - cards.getRealFlow();

			} else {
				flow = 0;
			}
		}
		if (cards.getSerPackage() instanceof NetPackage) {
			NetPackage type = (NetPackage) cards.getSerPackage();
			if (type.getFlow() > cards.getRealFlow()) {
				flow = type.getFlow() - cards.getRealFlow();

			} else {
				flow = 0;
			}
		}
		System.out.println("您的卡号是" + cards.getCardNumber() + "套餐内剩余");
		System.out.println("通话时长：" + time+"分钟");
		System.out.println("短信条数：" + smscount+"条");
		System.out.println("上网流量：" + flow+"MB");
	}

	/**
	 * 打印消费详单
	 * 
	 * @param number
	 */
	public void printAmountDetail(String number) {
		Writer fileWriter = null;
        try {
            // 现有消费列表中是否存在此卡号，是：true 否：false
        	 boolean isExist = false;
        	 if (consumInfos.get(number)!=null ) {
 				isExist=true;
 			}else {
                 System.out.println("对不起，不存在此卡号的消费记录，不能打印！");
             }
            if (isExist) {
            	fileWriter = new FileWriter("D:\\"+number+"消费记录.txt");
                Set<String> nu=consumInfos.keySet();
                Iterator<String> it=nu.iterator();
                // 存储指定卡号的所有消费记录
                List<ConsumInfo> infos =new ArrayList<ConsumInfo>();
                
            	infos=consumInfos.get(number);
                StringBuffer content= new StringBuffer("******" + number + "消费记录******\n");
                content.append("序号\t类型\t数据(通话(条)/上网(MB)/短信(条))\n");
                for (int i = 0; i < infos.size(); i++) {
                    ConsumInfo info =infos.get(i);
                    content.append((i + 1) + ".\t" + info.type + "\t"
                            + info.consumData + "\n");
                }
                fileWriter.write(content.toString());
                fileWriter.flush();
                System.out.println("消费记录打印完毕！");
            } 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
	}

	/**
	 * 套餐变更
	 * 
	 * @param number
	 * @param packNum
	 */
	public void changingPack(String number) {
		Scanner input = new Scanner(System.in);
		System.out.println("*****套餐变更*****");
		System.out.print("请输入要变更的套餐（1.话痨套餐 2.网虫套餐 3.超人套餐）");
		int choice = input.nextInt();
		switch (choice) {
		case 1:

			if (card.get(number).getSerPackage() instanceof TalkPackage) {
				System.out.println("对不起，您已经是该套餐的用户，无需换套餐！");
				break;
			} else {
				if (card.get(number).getMoney() < card.get(number).getSerPackage().getPrice()) {
					System.out.println("余额不足,请充值后再来办理！");
					break;
				} else {
					card.get(number).setRealSMSCount(0);// 短信条数
					card.get(number).setRealTalkTime(0);// 通话时间
					card.get(number).setRealFlow(0);// 上网流量
					card.get(number).setSerPackage(Common2.talkPackage);
					card.get(number).setMoney(card.get(number).getMoney()-58);
					card.get(number).setConsumAmount(card.get(number).getConsumAmount()+58);
					System.out.println("更换成功");
					break;
				}

			}
		case 2:
			if (card.get(number).getSerPackage() instanceof NetPackage) {
				System.out.println("对不起，您已经是该套餐的用户，无需换套餐！");
				break;
			} else {
				if (card.get(number).getMoney() < card.get(number).getSerPackage().getPrice()) {
					System.out.println("余额不足,请充值后再来办理！");
					break;
				} else {
					card.get(number).setRealSMSCount(0);
					card.get(number).setRealTalkTime(0);
					card.get(number).setRealFlow(0);
					card.get(number).setSerPackage(Common2.netPackage);
					card.get(number).setMoney(card.get(number).getMoney()-68);
					card.get(number).setConsumAmount(card.get(number).getConsumAmount()+68);
					System.out.println("更换成功");
					break;
				}
			}
		case 3:
			if (card.get(number).getSerPackage() instanceof SuperPackage) {
				System.out.println("对不起，您已经是该套餐的用户，无需换套餐！");
				break;
			} else {
				if (card.get(number).getMoney() < card.get(number).getSerPackage().getPrice()) {
					System.out.println("余额不足,请充值后再来办理！");
					break;
				} else {
					card.get(number).setRealSMSCount(0);
					card.get(number).setRealTalkTime(0);
					card.get(number).setRealFlow(0);
					card.get(number).setSerPackage(Common2.superPackage);
					card.get(number).setMoney(card.get(number).getMoney()-78);
					card.get(number).setConsumAmount(card.get(number).getConsumAmount()+78);
					System.out.println("更换成功");
					break;
				}
			}
		}

	}

	/**
	 * 办理退网
	 * 
	 * @param number
	 */
	public void delCard(String number) {
		if (isExistCard(number) == true) {
			card.remove(number);
			System.out.println("卡号" + number + "办理退网成功\n谢谢使用！");
			System.exit(0);
		} else {
			System.out.println("办理退卡失败！");
		}
	}

	/**
	 * 根据卡号和密码验证该卡是否注册
	 * 
	 * @param number
	 * @param passWord
	 * @return
	 */
	public boolean isExistCard(String number, String passWord) {
		if (card.size() != 0) {
			Set<String> numberKeys = card.keySet();
			Iterator<String> its = numberKeys.iterator();
			while (its.hasNext()) {
				String numberKey = its.next();
				MobileCard mobileCard = card.get(numberKey); // 根据key取出对应的值
				if (number.equals(mobileCard.getCardNumber()) && passWord.equals(mobileCard.getPassWord())) {
					System.out.println("登录成功！");
					return true;
				} else if (number.equals(mobileCard.getCardNumber()) == true
						&& passWord.equals(mobileCard.getPassWord()) == false) {
					System.out.println("密码错误！");
					return false;
				} else {
					System.out.println("卡号错误！");
					return false;
				}
			}

			return false;
		} else {
			System.out.println("该用户不存在!");
			return false;
		}

	}

	/**
	 * 根据卡号验证该卡是否注册
	 * 
	 * @param number
	 */
	public boolean isExistCard(String number) {
		if (card.containsKey(number)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 生成随机卡号
	 */
	public String CreateNumber() {
		Random random = new Random();
		// 记录现有用户中是否存在此卡号用户 是：true 否：false
		boolean isExist = false;
		String number = "";
		int temp = 0;
		do {
			isExist = false;
			do {
				temp = random.nextInt(100000000);
			} while (temp < 10000000);
			number = "139" + temp;
			Set<String> cardNumbers = card.keySet();
			for (String cardNumber : cardNumbers) {
				if (number.equals(cardNumber)) {
					isExist = true;
					break;
				}
			}

		} while (isExist);

		return number;
	}

	/**
	 * 添加指定卡号的消费记录
	 * 
	 * @param number
	 * @param info
	 */
	public void addConsumInfo(String number, ConsumInfo info) {
		listcon.add(info);
		consumInfos.put(number,listcon);
	}

	/**
	 * 根据用户选择的套餐序号返回套餐对象
	 * 
	 * @param packId
	 * @return
	 */
	public ServicePackage createPack(int packId) {
		switch (packId) {
		case 1:
			ServicePackage t = new TalkPackage(500, 0, 30, 58);
			return t;
		case 2:
			ServicePackage n = new NetPackage(0, 3*1024, 0, 68);
			return n;
		case 3:
			ServicePackage s = new SuperPackage(200, 1*1024, 50, 78);
			return s;
		}
		return null;

	}

}
